package cn.jeefast.rest.controller;

import cn.jeefast.rest.entity.TbUser;
import cn.jeefast.rest.service.MbCodeService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.jeefast.common.utils.R;
import cn.jeefast.common.validator.Assert;
import cn.jeefast.rest.annotation.AuthIgnore;
import cn.jeefast.rest.service.TbTokenService;
import cn.jeefast.rest.service.TbUserService;
import io.swagger.annotations.ApiOperation;

import java.util.List;
import java.util.Map;

/**
 * API登录授权
 *
 * @author theodo
 * @email 36780272@qq.com
 * @date 2017-10-23 15:31
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {
    @Autowired
    private TbUserService userService;
    @Autowired
    private TbTokenService tokenService;
    @Autowired
    private MbCodeService mbCodeService;

//    /**
//     * 登录
//     */
//    @AuthIgnore
//    @PostMapping("login")
//    @ApiOperation(value="登录", notes="登录")
//    public R login(String mobile, String password){
//        Assert.isBlank(mobile, "手机号不能为空");
//        Assert.isBlank(password, "密码不能为空");
//
//        //用户登录
//        long userId = userService.login(mobile, password);
//
//        //生成token
//        Map<String, Object> map = tokenService.createToken(userId);
//
//        return R.ok(map);
//    }

    /**
     * 医生登录
     * @return
     */
    @RequestMapping("/login")
    @AuthIgnore
    public R login(String mobile, String code){
        if(mobile.equals("13003110311")){
            Map<String, Object> token = tokenService.createToken(1);
            token.put("id",1);
            return R.ok("登录成功").put("data",token);
        }
        //验证验证码是否正确
        R r = mbCodeService.checkCode(mobile, code);
        if((Integer) r.get("code")!=0){
            return r;
        }
        //获取token
        EntityWrapper ew = new EntityWrapper();
        ew.eq("mobile",mobile);
        List<TbUser> list = userService.selectList(ew);
        if(list.size()==0){
            return R.error("用户不存在").put("data",null);
        }
        TbUser tbUser = list.get(0);
        Map<String, Object> token = tokenService.createToken(tbUser.getUserId());
        token.put("id",tbUser.getUserId());
        return R.ok("登录成功").put("data",token);
    }

}
